#include "MediaAnalysis.h"


MediaAnalysis::MediaAnalysis(QObject *parent)
    : QObject{parent}
{}

MediaInfo MediaAnalysis::analysisVideo(FileModel fileModel) {
    MediaInfo mediaInfo = MediaInfo();
    mediaInfo.mediaType = MEDIA_TYPE_UNKNOWN;
    AVFormatContext *formatContext = nullptr;

    //  打开文件
    if (avformat_open_input(&formatContext, fileModel.path.toStdString().c_str(), nullptr, nullptr) < 0) {
        //  关闭文件
        avformat_close_input(&formatContext);
        return mediaInfo;
    }
    // 读取文件的元数据
    if(avformat_find_stream_info(formatContext, nullptr) < 0) {
        //  关闭文件
        avformat_close_input(&formatContext);
        return mediaInfo;
    }

    //  查找视频流索引
    for(unsigned int i = 0; i < formatContext->nb_streams; ++i) {
        AVStream *stream = formatContext->streams[i];
        if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            // mediaInfo.videoStreams.append(stream);
            mediaInfo.videoStream = stream;
            mediaInfo.videoIndex = i;
        }
        if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
            mediaInfo.audioStreams.append(stream);
        }
    }
    if (mediaInfo.audioStreams.size() == 0 && mediaInfo.videoStream == nullptr) {
        avformat_close_input(&formatContext);
        return mediaInfo;
    }

    if (mediaInfo.audioStreams.size() > 0) {
        AVStream *audioStream = mediaInfo.audioStreams.first();
        mediaInfo.mediaType = MEDIA_TYPE_AUDIO;
        AVCodecParameters *codecParams = audioStream->codecpar;
        mediaInfo.channels = codecParams->ch_layout.nb_channels;
        mediaInfo.duration = audioStream->duration * av_q2d(audioStream->time_base);
        mediaInfo.format = QString::fromUtf8(formatContext->iformat->name);
        mediaInfo.sample_rate = codecParams->sample_rate;
    }

    if (mediaInfo.videoStream != nullptr) {
        AVCodecParameters *codecParams = mediaInfo.videoStream->codecpar;
        mediaInfo.mediaType = MEDIA_TYPE_VIDEO;
        mediaInfo.width = codecParams->width;
        mediaInfo.height = codecParams->height;
        mediaInfo.format = QString::fromUtf8(formatContext->iformat->name);
        mediaInfo.duration = mediaInfo.videoStream->duration * av_q2d(mediaInfo.videoStream->time_base);
        mediaInfo.framerate = codecParams->framerate;
        mediaInfo.frame_size = codecParams->frame_size;
    }
    avformat_close_input(&formatContext);
    return mediaInfo;
}
